/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler;

import com.jmex.bui.BComponent;
import com.jmex.bui.util.Rectangle;

public class ComponentUtils {

    /**
     * Enforces the position of the component to its parent's dimensions
     * @param parent parent bounds
     * @param bounds child bounds
     * @param new_x  new pos x
     * @param new_y  new pos y
     * @return new Rectangle
     */
    public static Rectangle enforceParentBounds( Rectangle parent, Rectangle bounds, int new_x, int new_y ) {

        // Fix negative values
        new_x = ( new_x < 0 ? 0 : new_x );
        new_y = ( new_y < 0 ? 0 : new_y );

        // Clamp width/height to parent width/height
        int new_width = ( bounds.width > parent.width ? parent.width : bounds.width );
        int new_height = ( bounds.height > parent.height ? parent.height : bounds.height );

        // Find out the max value of x and y
        int max_x = ( parent.width - new_width );
        int max_y = ( parent.height - new_height );

        // Fix x and y greater than max_x and max_y
        new_x = ( new_x > max_x ? max_x : new_x );
        new_y = ( new_y > max_y ? max_y : new_y );

        return new Rectangle( new_x, new_y, new_width, new_height );
    }

    /**
     * Enforces the position of the component to its parent's dimensions
     * @param parent parent bounds
     * @param bounds child bounds
     * @return new Rectangle
     */
    public static Rectangle enforceParentBounds( Rectangle parent, Rectangle bounds ) {
        return enforceParentBounds( parent, bounds, bounds.x, bounds. y );
    }

    /**
     * Enforces the position of the component to its parent's dimensions
     * @param component Component
     * @param new_x new pos x
     * @param new_y new pos y
     * @return new Rectangle
     */
    public static Rectangle enforceParentBounds( BComponent component, int new_x, int new_y ) {
        return enforceParentBounds( component.getParent().getBounds(), component.getBounds(), new_x, new_y );
    }
}
